package com.doyutu.seed.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.util.Assert;

/**
 * @author DoyuTu
 * @version 0.0.1
 * spring-boot-project-seed
 */
public class ServiceInfoUtil implements ApplicationListener<WebServerInitializedEvent> {

    private static WebServerInitializedEvent event;

    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        event = webServerInitializedEvent;
    }

    public static int getPort() {
        Assert.notNull(event, "WebServerInitializedEvent获取失败");
        int port = event.getWebServer().getPort();
        Assert.state(port != -1, "端口号获取失败");
        return port;
    }

    public static String getHostAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            throw new RuntimeException("获取HostAddress失败");
        }
    }
}
